
package network.httpProxy;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import network.utils.ProxyConstants;


/**
 * Start HTTP Local Proxy server..
 * 
 * @author http://arunava.in
 * 
 */
public class HTTPProxyServerStarter extends Thread {
	public static int started = 0;

	public static void main(final String[] args) {
		new HTTPProxyServerStarter().run();
	}

	public void run() {

		System.out.println(new Date() + " Encription Enabled ? "
				+ ProxyConstants.ENCRYPTION_ENABLED);

		if (ProxyConstants.logLevel >= 1) {
			System.out.println(new Date()
					+ " HTTPProxyServerStarter Started :: ");
		}

		try {
			final ServerSocket serverSocket = new ServerSocket(
					ProxyConstants.HTTPProxyPort);

			while (true) {
				started = 1;
				final Socket incoming = serverSocket.accept();
				new HTTPProxyStarterHelper(incoming).start();
				if (ProxyConstants.logLevel >= 1) {
					System.out
							.println(new Date()
									+ " HTTPProxyServerStarter New Client connected From  :: "
									+ incoming);
				}
			}
		} catch (final Exception e) {
			started = 2;
			System.out.println(new Date() + " HTTPProxyServerStarter Error :: "
					+ e);
		}

	}
}
/**
 * HTTP Proxy starter.
 * 
 */
class HTTPProxyStarterHelper extends Thread {
	Socket incoming;

	public HTTPProxyStarterHelper(final Socket incoming) {
		this.incoming = incoming;
	}

	public void run() {

		try {
			Socket outgoing = null;
			// If organization http present !!!!
			if (ProxyConstants.ORGANIZATION_HTTP_PROXY_HOST.equals("")) {
				outgoing = new Socket(ProxyConstants.webPHP_HOST_HTTP,
						ProxyConstants.webPHP_PORT_HTTP);
			} else {

				outgoing = new Socket(
						ProxyConstants.ORGANIZATION_HTTP_PROXY_HOST,
						ProxyConstants.ORGANIZATION_HTTP_PROXY_PORT);
			}

			// -->
			final HTTPProxyThreadBrowser thread2 = new HTTPProxyThreadBrowser(
					outgoing, incoming);
			thread2.start();
			// <----
			final HTTPProxyThreadServer thread1 = new HTTPProxyThreadServer(
					outgoing, incoming);
			thread1.start();
		} catch (final Exception e) {
			if (ProxyConstants.logLevel >= 1) {
				System.out.println(new Date()
						+ " HTTPProxyServerStarter Error :: " + e);
			}
		}
	}

}
